﻿using System;
using System.Globalization;
using System.Web.Routing;
using ManagedUIFlow.Properties;

namespace ManagedUIFlow.Model
{
    public class ApplicationController
    {        
        private static readonly ApplicationController DefaultCurrent = new ApplicationController();
        private CommandBuilder _commandBuilder;

        public static ApplicationController Current
        {
            get
            {
                return DefaultCurrent;
            }            
        }

        public CommandBuilder CommandBuilder
        {
            get
            {
                if (_commandBuilder == null)
                {
                    _commandBuilder = CommandBuilder.Current;
                }
                return _commandBuilder;
            }
            set
            {
                _commandBuilder = value;
            }
        }       
          
        public virtual void Execute(RequestContext requestContext,  ManagedFlow flow)
        {
            if (requestContext == null) throw new ArgumentNullException("requestContext");
            if (flow == null) throw new ArgumentNullException("flow");

            // Instantiate the command and call Execute                             
            var factory = CommandBuilder.GetCommandFactory();
            var command = factory.CreateCommand(requestContext, flow);
            if (command == null)
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        Resources.ControllerBuilder_FactoryReturnedNull,
                        factory.GetType(),
                        flow));

            try
            {
                command.Execute(flow);
            }
            finally
            {
                factory.ReleaseCommand(command);
            }
        } 
    }
}